package ssf.app.action;

import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import ssf.app.form.UploadFileForm;
import ssf.core.Constants;
import ssf.core.util.CalendarUtil;
import ssf.core.util.CharacterUtil;
import ssf.core.util.CommonUtil;

public class UploadFileAction extends BaseAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		// 将form转换为UploadFileForm Bean类型
		UploadFileForm formFile = (UploadFileForm) form;
		// 从FormBean中取得文件
		FormFile file = formFile.getFile();
		// 创建文件输出流对象
		FileOutputStream fileOutput = null;
		String extName = "";
		String srcName = file.getFileName();
		try {
			if (file == null || file.getFileSize() == 0) {
				setResult(request, "ERROR");
				addMessage(request, "无意义上传，请返回!");
				addRedirURL(request, "返回", "@back");
				return mapping.findForward(EXECUTE_RESULT);
			} else { // 文件不为空时进行上传操作
				// 取扩展名
				int pot = file.getFileName().lastIndexOf(".");
				if (pot != -1) {
					String tmp = file.getFileName().substring(pot);
					extName = tmp.substring(1, tmp.length());
					srcName = srcName.substring(0, pot);
				}
				// 设定文件保存的位置和命名
				String fileURL = "/uploadfiles/"
						+ CalendarUtil.getCurrentTime()
						+ CharacterUtil.getRandomString2(5) + "." + extName;
				// 向既定位置设置输出流
				fileOutput = new FileOutputStream(getServlet()
						.getServletContext().getRealPath(fileURL));
				// 文件写操作
				fileOutput.write(file.getFileData());
				// 写入数据库
				getServMgr().getFileService().addFile(srcName, extName,
						file.getContentType(), file.getFileSize(), fileURL);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fileOutput != null) {
				fileOutput.flush();
				fileOutput.close();
			}
		}
		return mapping.findForward("SUCCESS");
	}
}
